<?php

require("../_db.php");

function selfURL() {
	$protocol = 'http';
	$port = ($_SERVER["SERVER_PORT"] == "80") ? ""
		: (":".$_SERVER["SERVER_PORT"]);
	return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
}

session_start();

# We require the library
require("../facebook/facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
    'appId'  => '127661427389840',
    'secret' => 'f864f1d009c17d98b7b14050b1ac2283',
    'cookie' => true
));

Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;

// Get User ID
$user = $facebook->getUser();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
	$user_likes = $facebook->api('/me/likes');
	$friends = $facebook->api('/me/friends');
	
	foreach($user_likes['data'] as $user_like)
	{
		$q = " SELECT id FROM user_likes WHERE facebook_page_id = '".$user_like['id']."' AND facebook_user_id = '".$user_profile['id']."'";
		if ($ok = mysql_query($q))
		{
			if (!mysql_num_rows($ok))
			{
				$q1 = " INSERT INTO user_likes (id, facebook_user_id, facebook_category, facebook_page, facebook_page_id)
				VALUES (0, '".$user_profile['id']."', '".mysql_real_escape_string($user_like['category'])."', '".mysql_real_escape_string($user_like['name'])."', '".$user_like['id']."')";
				if (!mysql_query($q1)) die(mysql_error());
			}			
		}
	}
	
	/*if (!isset($_SESSION['recomandareid']))
	{
		$q = " INSERT INTO recomandari (id, fb_id, fb_name, fb_friend_id, fb_friend_name, fb_gender)
			VALUES (0, '".$user_profile['id']."', '".$user_profile['name']."', '', '', '".$user_profile['gender']."') ";
		if (!mysql_query($q)) die(mysql_error());
		$_SESSION['recomandareid'] = mysql_insert_id();
	}*/
	
  } catch (FacebookApiException $e) {
    error_log($e);
	echo $e;
    $user = null;
  }
}

// Login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
$link = str_replace('127.0.0.1', 'localhost', selfURL());
  //$loginUrl = $facebook->getLoginUrl();
  $loginUrl = $facebook->getLoginUrl(array(
	'req_perms' => 'likes',
    'next' => $link,
    'cancel_url' => $link
  ));
  $loginUrl = str_replace('127.0.0.1', 'localhost', $loginUrl);
  header("Location: {$loginUrl} ");  
}

// $user_profile;
// $user_likes;
// $friends;

//var_dump($user_likes);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>SAC project</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
	<script src="js/jquery.popupwindow.js"></script>
	<script src="js/jquery.lightbox_me.js"></script>
    <link href="style.css" rel="stylesheet" type="text/css" />
	<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
	var rec_id = -1;
	var step = 0;
	var maxstep = 6;
	var no_results = 3;
	$(document).ready(function() {
		$('.dialog-box').lightbox_me({
			centered: true, 
			onLoad: function() { 
				$('#sign_up').find('input:first').focus()
			}
		});
		//e.preventDefault();
	
        $( "#slider" ).slider({
			animate:"fast",
			range:"min",
			value:1,
			min:1,
			max:10,
			slide: function(event,ui)
			{
				$( "#amount" ).html(ui.value+" / 10");	
			}
		});
		$('.ui-slider-handle').append('<div class="test"><div id="amount" style="color: red;width:150px; font-weight: bold;"/></div>');
	});	
	
	function nextStep() {
		$('.box-chestionar').hide();
		$('.friends-list').hide();
		$('.question'+step).fadeIn();
		var percentage = 100 * step / (maxstep+1);
		$('#slider .ui-slider-handle').css('left',percentage+'%');
		$('#slider .ui-slider-range').css('width',percentage+'%');
	}
	function showResults() {
		$('.box-chestionar').hide();
		$('#slider').hide();
		
			$.get("../ajax/get-rec-gift.php", { id_rec: rec_id, id_excl: '' },
			function(a) {
				if (a == -1) 
				{
					$( "#error-get-gift" ).dialog({
						modal: true,
						buttons: {
							Ok: function() {
								$( this ).dialog( "close" );
							}
						}
					});
				}
				else
				{
					var gifts = $.parseJSON(a);
					$.each(gifts, function(k, gift) {
						$('#results').append('<li><a href="'+gift.link+'" target="_blank"><img src="'+gift.poza+'" /> <span class="gift-name">'+gift.nume+'</span></a>');
					});
				}
			});
		
		$('#results').fadeIn();
	}
	function newRec(fb_id, fb_name, fb_gender, fb_friend_id, fb_friend_name) {
		$.post("../ajax/new-rec.php", { fb_id: fb_id, fb_name: fb_name, fb_gender: fb_gender, fb_friend_id: fb_friend_id, fb_friend_name: fb_friend_name },
		function(a) {
			if (a == -1) 
			{
				$( "#error-new-rec" ).dialog({
					modal: true,
					buttons: {
						Ok: function() {
							$( this ).dialog( "close" );
						}
					}
				});
			}
			else
			{
				rec_id = parseInt(a);
				step++;
				nextStep();
			}
		});
	}
	function saveAns(id_atribut, valoare, scor) {
		$.post("../ajax/save-ans.php", { id_atribut: id_atribut, valoare: valoare, id_recomandare: rec_id, scor: scor },
		function(a) {
			if (a == -1) 
			{
				$( "#error-save-ans" ).dialog({
					modal: true,
					buttons: {
						Ok: function() {
							$( this ).dialog( "close" );
						}
					}
				});
			}
			else
			{
				step++;
				//console.log(step+' '+maxstep);
				if (step > maxstep) showResults();
				else nextStep();
			}
		});
	}
    </script>
</head>
<body>

 <div id="header">
		<div id="bg-logo" class="left">
			<div class="gift centru">
			
			</div>
		</div>
		<div class="text_logo">
			Get-A-Gift
		</div>
		
 </div>
 <div class="green_line"></div>
 <div class="dark_green"></div>

<!-- error messages -->
<div id="error-new-rec" title="Error" style="display: none">
    <p>
        <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 50px 0;"></span>
        An error occured when trying to set a new recommendation
    </p>
</div>

<div id="error-save-ans" title="Error" style="display: none">
    <p>
        <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 50px 0;"></span>
        An error occured when trying to save the answer
    </p>
</div>

<div id="error-get-gift" title="Error" style="display: none">
    <p>
        <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 50px 0;"></span>
        An error occured when trying to get a gift recommendation
    </p>
</div>
<!-- /error messages -->

<!-- success messages -->
<!-- /success messages -->
 
<div id="container" class="centru">
	

	
	<div id="main">

	<?php if (!$user) { ?>
	<div class="dialog-box">
	<a class="facebooklogin" href="http://localhost/subversion/facebook/">LOGIN WITH FACEBOOK</a>
		<script type="text/javascript">
		$('.facebooklogin').popupWindow({ 
			width:'800',
			height:'700',
			top:50,
			centerBrowser:1
		});	
		</script>
	</div>
	<?php } ?>
	
	<?php if ($user) { ?>
	<div id="middle-friends">
		<ul class="friends-list">
		<?php
		foreach( $friends['data'] as $friend ) {
			?>
			<li rel="<?php echo $friend['id']; ?>" onclick="newRec(<?php echo $user_profile['id']; ?>, '<?php echo $user_profile['name']; ?>', '<?php echo $user_profile['gender']; ?>', <?php echo $friend['id']; ?>, '<?php echo $friend['name']; ?>')"><span class="friend-name"><?php echo $friend['name']; ?></span></br>	<img src="http://graph.facebook.com/<?php echo $friend['id']; ?>/picture" /></li>
			<?php
		}
		?>
		</ul>
		</div>
	<?php
	} else {/* ?>
	<div class="fb-login-button" data-show-faces="false" data-width="200" data-max-rows="1"></div>
	<? 
		<div class="box-chestionar">
			<h2>Cui doriti sa cumparati acest cadou ?</h2>
			<form name="chestionar" id="chestionar" action="#" method="POST">
				<input type="radio" name="sex" value="ea"/>femeie<br />
				<input type="radio" name="sex" value="el"/>barbat<br />
				<br />
				<input type="button" value="Continua" />
			</form>
		</div>
	<?php */} ?>
	
	<?php /*<div class="box-chestionar">
			<h2>Cui doriti sa cumparati acest cadou ?</h2>
			<form name="chestionar" id="chestionar" action="#" method="POST">
				<input type="radio" name="sex" value="ea"/>femeie<br />
				<input type="radio" name="sex" value="el"/>barbat<br />
				<br />
				<input type="button" value="Continua" />
			</form>
		</div>*/ ?>
<!-- questions -->
<div id="bg_slider">
		<!-- question 1 -->
			
		<div class="box-chestionar question1" style="display: none">
			<h2>Ce prefera prietenul/prietena dvs sa faca in timpul liber?</h2><?php // social ?>
			<form name="chestionar" id="chestionar" class="text-center">
				<input type="radio" name="answer1" value="extravertit" id="answer11" /> <label for="answer11">sa iasa cu prietenii</label><br />
				<input type="radio" name="answer1" value="introvertit" id="answer12" /> <label for="answer12">sa se uite la televizor</label><br />
				<br />
				<input type="button" value="Continua" class="answerquestion" onclick="var p = ''; if($('input[name=answer1]:radio:checked').val() == 'extravertit') p = '1,1,1,1,1,1.61,1.61'; else p = '1,1,1,1.61,1,1,1'; saveAns(10, $('input[name=answer1]:radio:checked').val(), p);" />
			</form>
		</div>
		<!-- /question 1 -->

		<!-- question 2 -->
		<div class="box-chestionar question2" style="display: none">
			<h2>Atunci cand trebuie sa ia o decizie, prietenul dvs:</h2><?php // ratiune ?>
			<form name="chestionar" id="chestionar">
				<input type="radio" name="answer2" value="intuitiv" id="answer21" /> <label for="answer21">reactioneaza imediat, dupa primul impuls</label><br />
				<input type="radio" name="answer2" value="rational" id="answer22" /> <label for="answer22">gandeste problema indelung si abia apoi actioneaza</label><br />
				<br />
				<input type="button" value="Continua" class="answerquestion" onclick="var p = ''; if($('input[name=answer1]:radio:checked').val() == 'intuitiv') p = '1,1,1,1,1.61,1,1'; else p = '1,1,1,1.61,1,1,1'; saveAns(11, $('input[name=answer2]:radio:checked').val(), p)" />
			</form>
		</div>
		<!-- /question 2 -->

		<!-- question 3 -->
		<div class="box-chestionar question3" style="display: none">
			<h2>Stilul vestimentar al prietenului dvs este:</h2><?php // sofisticat ?>
			<form name="chestionar" id="chestionar">
				<input type="radio" name="answer3" value="sofisticat" id="answer31" /> <label for="answer31">elegant</label><br />
				<input type="radio" name="answer3" value="pragmatic" id="answer32" /> <label for="answer32">casual</label><br />
				<br />
				<input type="button" value="Continua" class="answerquestion" onclick="var p = ''; if($('input[name=answer1]:radio:checked').val() == 'sofisticat') p = '1,1,1,1,1.61,1,1'; else p = '1.61,1,1,1,1,1,1'; saveAns(12, $('input[name=answer3]:radio:checked').val(), p)" />
			</form>
		</div>
		<!-- /question 3 -->

		<!-- question 4 -->
		<div class="box-chestionar question4" style="display: none">
			<h2>De obicei, prietenul dvs:</h2><?php // rabdare ?>
			<form name="chestionar" id="chestionar">
				<input type="radio" name="answer4" value="nerabdator" id="answer41" /> <label for="answer41">se plictiseste foarte repede</label><br />
				<input type="radio" name="answer4" value="rabdator" id="answer42" /> <label for="answer42">are o rabdare uimitoare</label><br />
				<br />
				<input type="button" value="Continua" class="answerquestion" onclick="var p = ''; if($('input[name=answer1]:radio:checked').val() == 'nerabdator') p = '1,1,1,1,1,1.61,1'; else p = '1,1,1,1.61,1,1,1';  saveAns(13, $('input[name=answer4]:radio:checked').val(), p)" />
			</form>
		</div>
		<!-- /question 4 -->

		<!-- question 5 -->
		<div class="box-chestionar question5" style="display: none">
			<h2>Valoarea care il defineste cel mai bine pe prietenul dvs este:</h2><?php // traditionalitate ?>
			<form name="chestionar" id="chestionar">
				<input type="radio" name="answer5" value="traditionalist" id="answer51" /> <label for="answer51">traditionalismul</label><br />
				<input type="radio" name="answer5" value="modern" id="answer52" /> <label for="answer52">creativitatea</label><br />
				<br />
				<input type="button" value="Continua" class="answerquestion" onclick="var p = ''; if($('input[name=answer1]:radio:checked').val() == 'traditionalist') p = '1,1,1,1.61,1.61,1,1.61'; else p = '1,1,1,1,1.61,1.61,1'; saveAns(14, $('input[name=answer5]:radio:checked').val(), p)" />
			</form>
		</div>
		<!-- /question 5 -->

		<!-- question 6 -->
		<div class="box-chestionar question6" style="display: none">
			<h2>Prietenul dvs este, mai degraba, o persoana:</h2><?php // familist ?>
			<form name="chestionar" id="chestionar">
				<input type="radio" name="answer6" value="familist" id="answer61" /> <label for="answer61">familista</label><br />
				<input type="radio" name="answer6" value="individualist" id="answer62" /> <label for="answer62">individualista</label><br />
				<br />
				<input type="button" value="Continua" class="answerquestion" onclick="var p = ''; if($('input[name=answer1]:radio:checked').val() == 'familist') p = '1.61,1.61,1,1,1,1,1'; else p = '1,1,1,1,1.61,1,1'; saveAns(15, $('input[name=answer6]:radio:checked').val(), p)" />
			</form>
		</div>
</div>
<!-- /question 6 -->
<!-- /questions -->
	<ul id="results" style="display: none">
	</ul>
	
	<div id="slider"></div>		
	</div>
</div>



 
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=127661427389840";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
 
</body>
</html>